// import '@/styles/dist.css'
import tailwindStyles from '@/styles/dist.css?raw'
import setupPlugins from '@/plugins'
import { createApp } from 'vue'
import App from './App.vue'
import { useContent } from './components/content/useContent'
const zIndex = ref(1)
// 定义自定义元素类
class HangExtension extends HTMLElement {
  shadowRoot!: ShadowRoot
  /**鼠标点击的位置 */
  clickedPosition: { x: number; y: number } = { x: 0, y: 0 }
  /**是否显示 */
  show: boolean = false
  constructor() {
    super()
    this.init()
  }

  init() {
    this.setExtensionStyle()
    this.mount()
    this.addEventListener()
  }
  /**挂载组件 */
  mount() {
    // 创建 shadow root
    this.shadowRoot = this.attachShadow({ mode: 'open' })
    const app = createApp(App)
    app.use(setupPlugins)
    app.provide('app', this)
    const vm = app.mount(document.createElement('div'))
    this.shadowRoot.appendChild(vm.$el)
    document.documentElement.appendChild(this)
    // 创建 <style> 标签并注入 Tailwind CSS
    const style = document.createElement('style')
    style.textContent = tailwindStyles as string
    this.shadowRoot.appendChild(style)
  }

  /**获取挂载的节点 */
  getMountedElement() {
    // 关键点：直接通过 shadowRoot 查询元素
    const appElement = this.shadowRoot.getElementById('App')
    return appElement
  }
  /**设置组件样式 */
  setExtensionStyle() {
    this.style.display = 'none'
    this.style.position = 'fixed'
    this.style.cursor = 'move'
    this.style.top = '0px'
    this.style.left = '0px'
    this.style.width = '0px'
    this.style.height = '0px'
    this.style.zIndex = `${zIndex.value}`
  }

  /**添加监听事件 */
  addEventListener(): void {
    window.addEventListener('click', (e: MouseEvent) => {
      const target = e.target as HTMLElement
      const tagName = target.tagName.toLowerCase()
      const type = 'type' in target ? (target as HTMLInputElement | HTMLButtonElement).type : undefined
      const id = target.id
      const classList = Array.from(target.classList).join(', ')
      console.log(`点击的元素标签名: ${tagName}`)
      this.render()

      if (tagName == 'button') {
        // if (target.className == 'btn btn-primary') {
        //   this.render()
        // }
      }
    })
  }

  /**设置插件位置 */
  setPluginPosition(e: MouseEvent): void {
    this.style.display = 'flex'
    this.clickedPosition = { x: e.clientX, y: e.clientY }
    zIndex.value++
  }

  render(): void {
    this.style.display = 'flex'
    // const el = this.getMountedElement()!
    // useContent(el)
  }
}

export type IApp = InstanceType<typeof HangExtension>
nextTick().then(() => {
  // 注册自定义元素
  customElements.define('hang-extension', HangExtension)
  document.documentElement.appendChild(new HangExtension())
})
